#include "../Base/stdafx.h"
#include "../Meshes/Mesh.h"
#include "LevelLoader.h"
#include "../XML/XmlLoader.h"
#include "../Base/StringUtil.h"
#include "../PhysX/PhysXObject.h"
#include "../PhysX/ForceField.h"
#include "../Forest/TreeNode.h"

void LevelLoader::Load( const tstring& level, Mesh* meshes, vector<PhysXObject*>& NXObjects )
{
	XMLLoader xmlFile(level);
	float width, length, height, posx, posy, posz;
	tstring diffmap, normalMap, specMap, name;
	MeshDesc::PhysxState NxState;
	do 
	{
		if(xmlFile.GetStartElement() == _T("BOX"))
		{
			width = StringUtil::ToFloat(xmlFile.GetValue(_T("width")));
			length = StringUtil::ToFloat(xmlFile.GetValue(_T("length")));
			height = StringUtil::ToFloat(xmlFile.GetValue(_T("height")));
			posx = StringUtil::ToFloat(xmlFile.GetValue(_T("posx")));
			posy = StringUtil::ToFloat(xmlFile.GetValue(_T("posy")));
			posz = StringUtil::ToFloat(xmlFile.GetValue(_T("posz")));
			name = xmlFile.GetValue(_T("name"));
		}else 	if(xmlFile.GetStartElement() == _T("MAPS")) {
			diffmap = _T("./Textures/") + xmlFile.GetValue(_T("diffuse"));
			normalMap = xmlFile.GetValue(_T("normal"));
			specMap = xmlFile.GetValue(_T("specular"));
			if(normalMap == _T("NONE"))
				normalMap = _T("./Textures/WhiteTex.dds");
			else
				normalMap = _T("./Textures/") + normalMap;
			if(specMap == _T("NONE"))
				specMap = _T("./Textures/WhiteTex.dds");
			else
				specMap = _T("./Textures/") + specMap;
			meshes->CreateBox(name, diffmap, normalMap, specMap, width, length, height, D3DXVECTOR3(posx, posy, posz), NxState);
		}else if(xmlFile.GetStartElement() == _T("PHYSX")) {
			if(xmlFile.GetValue(_T("state")) == _T("static"))
				NxState = MeshDesc::PhysxStatic;
			else
				NxState = MeshDesc::PhysxDynamic;
		}

		if(xmlFile.GetStartElement() == _T("FORCEFIELD"))
		{
			width = StringUtil::ToFloat(xmlFile.GetValue(_T("width")));
			length = StringUtil::ToFloat(xmlFile.GetValue(_T("length")));
			height = StringUtil::ToFloat(xmlFile.GetValue(_T("height")));
			posx = StringUtil::ToFloat(xmlFile.GetValue(_T("posx")));
			posy = StringUtil::ToFloat(xmlFile.GetValue(_T("posy")));
			posz = StringUtil::ToFloat(xmlFile.GetValue(_T("posz")));
			name = xmlFile.GetValue(_T("name"));
		}else if(xmlFile.GetStartElement() == _T("VELOCITY")) {
			float x = StringUtil::ToFloat(xmlFile.GetValue(_T("x")));
			float y = StringUtil::ToFloat(xmlFile.GetValue(_T("y")));
			float z = StringUtil::ToFloat(xmlFile.GetValue(_T("z")));
			NXObjects.push_back(new ForceField(name, D3DXVECTOR3(posx, posy, posz), D3DXVECTOR3(x, y, z), D3DXVECTOR3(width, height, length)));
		}
	} while (xmlFile.Next());
}